var brandList, pbcList;
var chk_value_str = "";//用于保存已选择的网点，
var chk_value_str_del = "";//用于删除已保存的网点id
var chk_value_str_edit = "";//用于保存已选择的网点，
$(function () {
	$(function () {
        $('[data-toggle="product-pic-popover"]').popover({
            animation: true,
            html: true,
            trigger: "hover",
            content: function () {
                return "<img class='img-product-cover' src='" + PicDomain + $(this).data("pic-uri") + "'/>";
            }
        });
    });
	
	
	//选择网点modal 全选
	//全选
	$("#selectAll").click(function() { 
		if($(this).is(':checked')){
			$("input[name='branch']").each(function() { 
				$(this).prop("checked", true); 
			});
		}else{
			$("input[name='branch']").each(function() { 
				$(this).prop("checked", false); 
			});
		}
	}); 
	
	//当列表中所有复选框选中，全选按钮选中，否则不选中
	var flag = 0;//未选中标记
	$("input[name='branch']").click(function(){
		
		$("input[name='branch']").each(function(){
			if(!$(this).is(':checked')){
				flag ++;
			}
		});
		if(flag > 0){
			$("#selectAll").prop("checked",false);
		}else{
			$("#selectAll").prop("checked",true);
		}
		flag = 0;//清空falg值
	});
	
	
	
	
	
    //新建奖品页面，选择完网点，确认
    $("#selectPro_confirm").click(function(){
    	//同时显示已选择的活动列表，显示位置：创建活动页面-->活动商品
    	//获取选中的记录id,根据id查询出列表，展示
    	var chk_value =[];
    	
    	$('input[name="branch"]:checked').each(function(){
    		chk_value.push($(this).val());
    		chk_value_str += $(this).val()+",";
    	}); 
    	if(chk_value.length == 0){
    		bootbox.balert("没有选中任何网点，请继续选择网点!");
    		return;
    	}else{
			var str = "";
			for(var i= 0; i<chk_value.length; i++){

				var id = chk_value[i];
				str += '<tr>' +
					'<td>'+chk_value[i] + '</td>'+
					'<td>'+ $(".name_" +id).text() + '</td>' +
					'<td>'+ $(".linkPhone_" +id).text() + '</td>' +
					'<td>'+ $(".address_" +id).text() + '</td>' +
					'<td>'+ $(".linkMan_" +id).text() + '</td>' +
					'<td><button type="button" class="btn btn-default btn-xs" onclick="delSelectedPro('+chk_value[i]+',this)" name="btn_delete_activity_product" data-activity-product-id= "' + chk_value[i] + '">删除</button></td>'
					'</tr>';

			};
			$('#prize_new_table').append(str);//新建奖品页面
			//$('#prize_edit_table').html(str);//奖品编辑页面
			
		}
    	
    });
    //奖品编辑页面，选择完网点，确认
    var oldSelectedArr = [];
    
    $("#prize_edit_table .priezeId").each(function(){
    	oldSelectedArr.push($.trim($(this).html()));
    });
    
    
    
    $("#selectPro_confirm_edit").click(function(){
    	//同时显示已选择的活动列表，显示位置：创建活动页面-->活动商品
    	//获取选中的记录id,根据id查询出列表，展示
    	function unique(arr){
        	var res = [];
    	   	 var json = {};
    	   	 for(var i = 0, l = arr.length; i < l; i++){
    	   	  if(!json[arr[i]]){
    	   	   res.push(arr[i]);
    	   	   json[arr[i]] = 1;
    	   	  }
    	   	 }
    	   	 return res;
        }
    	
    	
    	var chk_value =oldSelectedArr;
    	
    	$('input[name="branch"]:checked').each(function(){
    		chk_value.push($(this).val());
    		chk_value_str_edit += $(this).val()+",";
    	}); 
    	
    	chk_value = unique(chk_value);
    	if(chk_value.length == 0){
    		bootbox.balert("没有选中任何网点，请继续选择网点!");
    		return;
    	}else{
    		var str = "";
    		for(var i= 0; i<chk_value.length; i++){
    			
    			var id = chk_value[i];
    			str += '<tr>' +
    			'<td>'+chk_value[i] + '</td>'+
    			'<td>'+ $(".name_" +id).text() + '</td>' +
    			'<td>'+ $(".linkPhone_" +id).text() + '</td>' +
    			'<td>'+ $(".address_" +id).text() + '</td>' +
    			'<td>'+ $(".linkMan_" +id).text() + '</td>' +
    			'<td><button type="button" class="btn btn-default btn-xs" onclick="delSelectedPro('+chk_value[i]+',this)" name="btn_delete_activity_product" data-activity-product-id= "' + chk_value[i] + '">删除</button></td>'
    			'<td></td>'+
    			'</tr>';
    			
    		};
    		$('#prize_edit_table').html(str);//奖品编辑页面
    		
    	}
    	
    });
    
    
    function resetData(page){
		var keyword = $('input[name="keyword"]').val();

		page = page || 1;
		$.post("/prize/getBranchList?keyword=" + keyword + "&page=" +page, function (re) {
			var result = re.data, resultList=result.result;

			var str = "";
			for(var i=0; i<resultList.length; i++){

				var id = resultList[i].id;
				str += '<tr>' +
					'<td><input type="checkbox" name="branch" value="'+id+'" onclick="check_branch('+id+')" /></td>'+
					'<td>'+ id + '</td>'+
					'<td class="name_'+id+ '">'+ resultList[i].name + '</td>' +
					'<td class="linkPhone_'+id+ '">'+ resultList[i].linkPhone + '</td>' +
					'<td class="address_'+id+ '">'+ resultList[i].address+ '</td>' +
					'<td class="linkMan_'+id+ '">'+ resultList[i].linkMan + '</td>' +
					'</tr>';
			}
			$('#branch_modal').html(str);//奖品新建页面
			$('#branch_modal_edit').html(str);//奖品编辑页面
			resetPage(result.pageTotal, page);
		});
	}

	function resetPage(totalPage, currPage){
		var innerHTML = [];

		currPage = currPage || 1;

		innerHTML.push('<ul class="pagination pagination-sm no-margin">');

		if(currPage > 1){
			innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
		}

		if(currPage - 4 > 1){
			innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
		}

		for(var i = currPage - 3; i < currPage; i++){
			if(i > 1){
				innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
			}
		}

		innerHTML.push('<li class="active"><span>', currPage,'</span></li>')

		for(var i = currPage+1; i < currPage+3; i++){
			if(i < totalPage){
				innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
			}
		}

		if(currPage < totalPage - 3){
			innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
		}

		if(currPage < totalPage){
			innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
				'<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
		}

		innerHTML.push("</ul>")

		$("#page_model").data("total", totalPage).html(innerHTML.join(""));

	}

	resetPage(parseInt($("#page_model").data("total")));

	$("[name='pro_query']").click(function () {
			resetData(1);
	});
	$("#page_model").on("click", "li", function () {
		if($(this).hasClass("active")){
			return false;
		}

		var currPage = parseInt($("#page_model .active").text()),
			totalPage = $("#page_model").data("total");
		if($(this).hasClass("prev")){
			currPage--;
		} else if($(this).hasClass("next")){
			currPage++;
		} else if($(this).hasClass("bigPrev")){
			currPage -= 5;

			if(currPage < 1){
				currPage = 1;
			}
		} else if($(this).hasClass("bigNext")){
			currPage += 5;

			if(totalPage - currPage < 0){
				currPage = totalPage;
			}
		} else {
			currPage = parseInt($(this).text());
		}

		resetData(currPage);
	});
    
    //奖品类型为红包或优惠券，配送方式为自动发送
	//奖品类型为实物，配送方式为上门自提或物流配送
	$("[name='type']").change(function(){
		$("[name='shippingMethod']").find("option").remove();
		if($(this).val()==""){
			var Options = "<option value=''>请选择配送方式</option>";
			$("[name='shippingMethod']").append(autoOptions);
		}
		if($(this).val()==1 || $(this).val()==3){//红包、优惠券
			var autoOptions = "<option value='1' selected>自动发送</option>";
			$("[name='shippingMethod']").append(autoOptions);
			

			$('#site').hide();
			$('#selectedProDiv').hide();
		}
		if($(this).val() ==2){//实物
			var autoOptions = "<option value=''>请选择配送方式</option><option value='2'>上门自提</option><option value='3'>物流配送</option>";
			$("[name='shippingMethod']").append(autoOptions);
			
		}
		/*<option value="">请选择配送方式</option>
        <option value="1">自动发送</option>
        <option value="2">上门自提</option>
        <option value="3">物流发送</option>*/
	});
	//配送方式为上门自提时，才显示自提网点选择
	$("[name='shippingMethod']").change(function(){
		
		if($(this).val()==2){
			$('#site').show();
			$('#selectedProDiv').show();
		}else{
			$('#site').hide();
			$('#selectedProDiv').hide();
		}
	});
	
	
	//点击“新增奖品”按钮，
    $("[name='btn_new_prize']").click(function(){
    	window.location.href="/prize?add=1";
    });
    
    var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字
    //取消奖品
    $("[name='btn_cancel_new_prize']").click(function(){
		window.location.href="/prize";
	});
    
    //录入保存奖品
    $("[name='btn_save_new_prize']").click(function () {
        var form = window.form_new_prize;
        var name = form.name.value;
        if(!name){
        	bootbox.balert("奖品名称必须填写!");
    		return;
        }
        
        var type = form.type.value;
        if(!type){
        	bootbox.balert("奖品类型必须选择!");
    		return;
        }
        
        var price = form.price.value;
        if (!re.test(price)){
        	bootbox.balert("价格必须为数字!");
    		return false;
        }
        var stock = form.stock.value;
        if (!re.test(stock)){
        	bootbox.balert("库存必须为数字!");
    		return false;
        }
        var shippingMethod = form.shippingMethod.value;
        if(!shippingMethod){
        	bootbox.balert("配送方式必须选择!");
    		return;
        }
        var summary = form.summary.value;
        
        if(shippingMethod == 2){
        	//必须选择网点
        	if(chk_value_str == null ||chk_value_str == ""){
        		bootbox.balert("配送方式是上门自提，请选择网点!");
        		return;
        	}
        }
        $("#ctn_new_product_pics img").each(function () {
            pictures += $(this).data("picuri") + ",";
        });
        
        var selectedBranch = chk_value_str;
        
      //展示奖品图片
        var pictures = "";
        $("#ctn_new_product_pics img").each(function () {
            pictures += $(this).data("picuri") + ",";
        });

        
        if(pictures == ""){
        	bootbox.balert("奖品图片必须上传!");
        	return false;
        }
        if(summary == null || summary == ""){
        	bootbox.balert("奖品简介必须填写!");
        	return false;
        }
        var prize = {name: name, type: type, price: price, stock: stock, shippingMethod: shippingMethod, summary: summary,
        		selectedBranch:selectedBranch,image:pictures};
        $.postJsonBody("/prize", prize, function (re) {
            // tipper.success("已保存，请刷新页面");
            // $("#md_new_brand").modal("hide");
            window.location.href="/prize";
        })
    });
    
    //点击奖品列表中"编辑"按钮
    $("[name='btn_edit_prize']").click(function(){
    	var prizeId = $(this).data("prize-number");
    	window.location.href="/prize?prizeId="+prizeId;
    });

    //编辑奖品
    $("[name='btn_save_edit_prize']").click(function () {
        var form = window.form_edit_prize;
        var id = form.id.value;
        var name = form.name.value;
        if(!name){
        	bootbox.balert("奖品名称必须填写!");
    		return;
        }
        var type = form.type.value;
        if(!type){
        	bootbox.balert("奖品类型必须选择!");
    		return;
        }
        var price = form.price.value;
        if (!re.test(price)){
        	bootbox.balert("价格必须为数字!");
    		return false;
        }
        var stock = form.stock.value;
        var stock_temp = $("#stock1").val();
        if(stock_temp >= 0){
        	if (!/^[1-9]\d*$/.test(stock) && stock != 0){
            	bootbox.balert("库存必须为数字!");
        		return;
            }
        }else{
        	//var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字
        	//var t = /^(-?)\d+(\.\d?)$/;
        	var t = /^[\-]?[1-9]+\d*$/;
        	var b = t.test(stock);
        	if(!t.test(stock) && stock != 0){
        		bootbox.balert("库存允许负数和数字!");
        		return;
        	}
        }
        
        var shippingMethod = form.shippingMethod.value;
        if(!shippingMethod){
        	bootbox.balert("配送方式必须选择!");
    		return;
        }
        var summary = form.summary.value;
        
        if(shippingMethod == 2){
        	//必须选择网点
        	if((chk_value_str_edit == "") && ($("#regFlag").val()==0)){
        		bootbox.balert("配送方式是上门自提，请选择网点!");
        		return false;
        	}
        }
        var selectedBranch = chk_value_str_edit;//自提网点
        
      //展示奖品图片
        var pictures = "";
        $("#ctn_edit_product_pics img").each(function () {
            pictures += $(this).data("picuri") + ",";
        });
        if(pictures == ""){
        	bootbox.balert("奖品图片必须上传!");
        	return false;
        }
        if(summary == null || summary == ""){
        	bootbox.balert("奖品简介必须填写!");
        	return;
        }
        
        var prize = {id: id, name: name, type: type, price: price, stock: stock, shippingMethod: shippingMethod, 
        		summary: summary,selectedBranch:selectedBranch,image:pictures,delSelectedBranch:chk_value_str_del};
        $.putJsonBody("/prize/" + id, prize, function (re) {
            // tipper.success("已保存，请刷新页面");
            // $("#md_new_brand").modal("hide");
            window.location.href="/prize";
        })
    });

    //删除奖品
    $("[name='btn_delete_prize']").click(function () {
        var id = $(this).data("prize-id");
        bootbox.bconfirm("确定要删除这个奖品吗？", function (re) {
            if (re) {
                $.delete("/prize/" + id, function (re) {
                    if (re.data) {
                        // tipper.success("删除成功，请刷新页面");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    } else {
                        //tipper.danger("删除失败，请重试");
                    }
                });
            }
        });
    });

  //新建页面
    $("[name='btn_new_product_upload_pic']").click(function () {
        var uploaded_count = $("#ctn_new_product_pics").find("img").length;
        if (uploaded_count < 3) {
            $("#ipt_new_product_upload_pic").click();
        } else {
            bootbox.balert("奖品最多只能上传3张图片");
            return;
        }
    });
    $('#ipt_new_product_upload_pic').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=4",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
            	bootbox.bconfirm("确定要删除奖品图片吗？", function (re) {
            		if(re){
            			$imgEle.remove();
            		}
            	});
                
            });
            $("#ctn_new_product_pics").append($imgEle);
        }
    });
    //编辑页面
    $("[name='btn_edit_product_upload_pic']").click(function () {
    	var uploaded_count = $("#ctn_edit_product_pics").find("img").length;
    	if (uploaded_count < 3) {
    		$("#ipt_edit_product_upload_pic").click();
    	} else {
    		bootbox.balert("奖品最多只能上传3张图片");
    		return;
    	}
    });
    $('#ipt_edit_product_upload_pic').fileupload({
    	dataType: 'json',
    	url: "/upload/pic?type=4",
    	done: function (e, data) {
    		var res = data.jqXHR.responseJSON;
    		var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
    		$imgEle.click(function () {
    			bootbox.bconfirm("确定要删除奖品图片吗？", function (re) {
    				if(re){
    					$imgEle.remove();
    				}
    			});
    			
    		});
    		$("#ctn_edit_product_pics").append($imgEle);
    	}
    });
  
  
    
});

var flag1 = 0;
function check_branch(id){
	$("input[name='branch']").each(function(){
		if(!$(this).is(':checked')){
			flag1 ++;
		}
	});
	if(flag1 > 0){
		$("#selectAll").prop("checked",false);
	}else{
		$("#selectAll").prop("checked",true);
	}
	flag1 = 0;//清空falg值
}

// 奖品详情
$('#md_edit_prize').on('show.bs.modal', function (event) {
    var _e = $(event.relatedTarget);
    var id = _e.data("prize-id");
    var modal = $(this);
    var form = window.form_edit_prize;
    $.get("/prize/" + id, function (re) {
        var prize = re.data;
        form.id.value = prize.id;
        form.name.value = prize.name;
        form.type.value = prize.type;
        form.price.value = prize.price;
        form.stock.value = prize.stock;
        form.shippingMethod.value = prize.shippingMethod;
        form.summary.value = prize.summary;
    });
});


//选择完商品,点击删除按钮操作
function delSelectedPro(id,dom){
	
	chk_value_str = chk_value_str.substring(0,chk_value_str.length-1);
	var strArray = chk_value_str.split(",");
	chk_value_str = "";
	for(var i=0;i<strArray.length;i++){
		if(strArray[i]!=id){
			chk_value_str += strArray[i]+","
		}
	}
	
	$(dom).parent().parent().remove();
}
//编辑页面，删除已存在的自提网点
function delBranch(id,dom){
	chk_value_str_del += id+",";
	$(dom).parent().parent().remove();
}

//查询条件重置
$("#search_reset").click(function(){
	$("input").val("");
    $("select").val("");
});
